//app.js
const {alert,json2string,log,jump,ab2hex,cubeIsOnline,
  throttle,currentPageName,whenOfflineSaveInfo,whenOnlineSaveInfo,getPageInstance,timeFormat,setCubeInfo,getCubeInfoJson} = require('./utils/util');
const {closeCube,reply,lastCubeDeviceId,parseRes,specialData,serviceId,cubeSendUuidNotify} = require('./utils/bluetooth');
const eventEnhance = require('./utils/eventEnhance');
const {Event} = require('./utils/constant');
const _ = require('./utils/underscore');

App({
  onLaunch: function (options) {

    const that = this;

    // const content = _.reduce( [ 1, 2, 3 ], function( memo, num ) { return memo + num; }, 0 )+'';
    // console.log(content)

    // wx.clearStorageSync();

    // 因为wx.onBluetoothAdapterStateChange的特殊性，
    // 强制整个小程序只能openBluetoothAdapter一次，
    // 且open失败后，所有的api也是可以使用的（todo 待验证）
    //参考https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxopenbluetoothadapterobject

    wx.openBluetoothAdapter({
      success:function () {
        log('bluetoothAdapterState success');
        that.globalData.bluetoothLastAvailable = true;
      },
      fail:function (res) {
        that.globalData.bluetoothLastAvailable = false;
        log(`!!!openBluetoothAdapter fail. ${json2string(res)}`);
        jump({pageName:'bluetoothClosed'});
      }
    });

    wx.removeStorageSync('needConnect');
    wx.setStorageSync('autoReconnect',1);


    wx.onBluetoothAdapterStateChange(function (res) {

      //  搜索api的start、stop会触发discovering的变化

      const {available, discovering} = res;

      if (available !== that.globalData.bluetoothLastAvailable) {
        if(!available){
          whenOfflineSaveInfo(); //解决场景：列表页是第1个页面，详情页连接着cube，在列表页断开蓝牙，点击同一个cube
        }
        that.event.emit(Event.BluetoothAdapterStateChange,available);
        that.globalData.bluetoothLastAvailable = available;
      }
    });

    //订阅操作成功后需要设备主动更新特征值的value，才会触发 wx.onBLECharacteristicValueChange 回调。
    wx.onBLECharacteristicValueChange(function (res) {
      // cube->mobile
      const {value} = res;
      const valueJson = parseRes(ab2hex(value));
      const {command, seqNum} = valueJson;
      [176,177].indexOf(command)!==-1?console.log(`cube对密码或主动请求数据时的响应，不需要mobile回复`):console.log(`收到了cube的数据，需回复 command=${command}`);
      reply({command,seqNum,deviceId:lastCubeDeviceId()});
      that.dataTransfer(res);
      //that.event.emit(Event.BLECharacteristicValueChange,res);
    });

    wx.onBLEConnectionStateChange(function(res) {
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`);
      const {connected,deviceId} = res;
      const autoReconnect = wx.getStorageSync('autoReconnect');
      if(connected){
        // whenOnlineSaveInfo();
      }else{

        console.log(`when connected is ${connected}.wx.onBLEConnectionStateChange. autoReconnect=${autoReconnect}`);
        that.event.emit(Event.BLEConnectionStateChange,{connected,deviceId}); //deviceId会变

        //  cube切换、蓝牙配对、扫一扫、cube放入dock、cube关机、蓝牙关闭
        // 都会导致离线，但不都需要重连，所以重连的代码不适合写在这。

        if(currentPageName().toLowerCase()==='deviceInfo'.toLowerCase() && autoReconnect-0===1){
          that.event.emit(Event.BLEDiscoveryWhenOffline);
        }

        // wx.setStorageSync('autoReconnect',1);

        whenOfflineSaveInfo();

      }

    });

  },
  dataTransfer:function (res) {
    const that = this;
    const serialNumber = wx.getStorageSync('lastCubeSerialNumber')+'';

    // cube->mobile
    const {value} = res;
    const valueJson = parseRes(ab2hex(value));
    const {command, seqNum} = valueJson;
    let data;
    // const deviceInfoInstance = getPageInstance('deviceInfo');
    if (command === 2 || command === 3) {
      //特殊处理，  甲醛:ffff、pm2.5:ffff，其它都为0时
      if (specialData(valueJson)) {
        log(`@@@@@@@@@@@@@@@@valueJson:${JSON.stringify(valueJson)}`);
      } else {
        data = Object.assign({}, valueJson, {matchStatus: 3, timeDesc: timeFormat(valueJson.timeStamp)});
        that.event.emit(Event.DataTransfer,{id:serialNumber,info:data});
        setCubeInfo({serialNumber, info: data});
      }
    } else if (command === 0xb4) {
      log(`设置名字cube->mobile：${valueJson.status}`);
    } else if (command === 4) {
      log(`!!!!!!!!!!!Cube Upload Sensor History Data To Mobile. command=${command}`)
    } else if (command === 5) {
      log(`........command=5时,${JSON.stringify(valueJson)}`);
      data = Object.assign({}, valueJson, {matchStatus: 3});
      that.event.emit(Event.DataTransfer,{id:serialNumber,info:data});
      setCubeInfo({serialNumber, info: data});
    }
  },
  event:new eventEnhance(),
  onShow:function (options) {
    const that = this;
    that.globalData.appInForground = true;
    const online = cubeIsOnline();
    if(!online){
      wx.setStorageSync('needConnect',1);
    }
    //wx.setStorageSync('autoReconnect',1);
    console.log(`onShow 结束 online=${online}`)

  },
  onHide:function(){

    // test();

    this.globalData.appInForground = false;
    // this.globalData.disconnecting = true;
    wx.setStorageSync('autoReconnect',0);
    console.log('app onHide中成功设置autoReconnect为0');
    wx.setStorageSync('needConnect',0);
    wx.stopBluetoothDevicesDiscovery();
    const online = cubeIsOnline();
    const cubeIsDisconnecting = wx.getStorageSync('cubeIsDisconnecting');
    console.log(`app onHide时，设备${online?'在线':'离线'}`);
    if(cubeIsDisconnecting === 1){
      console.log('上一次cube的断开操作.未.完成');
    }else if(cubeIsDisconnecting === 0){
      console.log('上一次cube的断开操作.已.完成');
    }else{
      console.log('cube断开？？？');
    }
    if(cubeIsDisconnecting-0!==1 && online){
      const {deviceId} = getCubeInfoJson();
      console.log(`deviceId=${deviceId}`);
      closeCube(function () {
        console.log('触发了closeCube函数的回调');
      })
    }
    console.log('onHide 结束');
  },
  globalData: {
    bluetoothLastAvailable:false,
    appInForground:false
  }
});